/**
 * @author xiaowei
 * @date 2017年5月2日
 */
Ext.define('App.view.common.Window', {
    extend: 'App.view.BaseWindow',
    mixins: [
		'App.view.common.CommonFun',
		'App.view.common.ComponentFactory'
	],
    _isView: false,//是否是查看功能
    requires: [
        'App.view.common.Waitwindow'
    ],
    xtype: 'commonwindow',
    openValidation: false,//是否开启验证，用在获取页面参数的时候
    isGetChangeValue: false,//提交时，获取参数是否只获取修改的值。
    isWaitWindow: true,//在窗口完全打开前是否需要弹出一个等待窗口，默认弹出
    autoPrompt:true,//操作成功是否自动弹出浮框提示，默认true提示
	/*
	approvalProcessParam: '',//审批流程
	_targetObject: '',//执行参数查询的对象
	_confsOveride: {},//可以把属性叠加给_confs配置，如_confs中已经存在该属性，将不会被复制
	_record: '',//来自列表选中的第一条记录
	_trigger: '',保存触发对象引用，例如点击按钮触发新增窗口，那么按钮便是触发对象
	_confs: {
		dataMapping: [],
		url: '',
		form: {
			components:[
				['materielName','materielCode']
			]
		},
		grid: {}
	},
	items: [
		{xtype: 'fieldset',collapsible: true,height: 100, layout: 'fit',
			padding: '10px',
			margin: '0 10 0 0',
			title: '基本信息',
			items: [
				{name: 'inspspecsetForm',xtype:'inspspecsetForm', autoSetSelect: true,isParam: true}
			]
		},
		
		{name: 'sizeSpecGrid',xtype:'inspspecsetSizeSpecGrid',isParam: true
			header: {title: {text:'1-尺寸',maxWidth : 60},xtype: 'commonheader',items: [
				{xtype: 'textfield',fieldLabel: '显示参数',name: 'showView'},
				{xtype: 'textfield',fieldLabel: '显示字段',name: 'showf'}
			]}
		}
	],
	*/
	autoShow : false,
	layout: {
		type: 'vbox',
		align: 'stretch'
	},
	modal : true,
	maximizable:true,
	scrollable:'y',
	initComponent: function(){
		//this.waitWindow = this._createWaitWindow();
        this.initPhone();
		this._setConfs();
		this.items = this._getItems();
		var buttons = this._getButtons();
		if(!Ext.isEmpty(buttons)){
			this.buttons = buttons;
		}
		
		this.callParent();
		this.on({
			beforeShow: function() {
				if(this.waitWindow && !this.waitWindow.isDestroyed){
					this.waitWindow.close();
				}
			},
			beforeclose: function(th){
				this.hide();
				if(th.isHiddenClose){
					return true;
				}
				setTimeout(function(){
					th.isHiddenClose = true;
					th.close();
				},10);
				return false;
			}
		});
	},
    initPhone:function () {
        if(!Ext.platformTags.desktop) {
            this.maximizable = false;
            this.maximized = true;
        }
    },
	_createWaitWindow: function(){
		if(!this.isWaitWindow){
			return ;
		}
		return Ext.create({
			xtype: 'commonWaitwindow',
			width: this.width,
			height:this.height,
			header: this.header
		});
	},
	
	_show: function(){
		var me = this;
		setTimeout(function(){
			me.show();
		},10);
	},
	
	_getItems: function(){
		var items = [];
		if(this.items){
			items = Ext.clone(this.items);
			this._initItems(items);
		}
		return items;
	},
	
	_initItems: function(items){
		var temp, i, confObj,
		confs = this._confs;
		for(i = 0; i<items.length; i++){
			if(items[i]){
				items[i].openValidation = this.openValidation;
				if(!items[i].hasOwnProperty('_isView')){
                    items[i]._isView = this._isView;
                }
				if(items[i].confsName){
					this._copyDataMapping(items[i], confs[items[i].confsName]);
				}
                items[i]._trigger = this._trigger;
				if(items[i].autoSetSelect && this._record){

					items[i]._record = this._record;
					temp = Ext.create(items[i]);
					
					if(temp.is('form')){
						temp.setValues(this._record);
					}
					
					items[i] = temp;
				}

				if(Ext.isArray(items[i].items)){
					this._initItems(items[i].items);
				}
			}
		}
	},
	
	_getButtons: function(){
		var me = this;
		if(!this.buttons){
			return '';
		}
		var btns =  Ext.clone(this.buttons);
		var buttons = [], button, temp;
		for(var i = 0; i<btns.length; i++){
			temp = btns[i];
			if(Ext.isString(temp)){
				button = me._getButton(temp);
				
			}else if(Ext.isObject(temp)){
				button = me._getButton(temp.name);
				if(button){
					button = Ext.applyIf(temp, button);
				}else{
					button = temp;
				}
			}
			buttons.push(button);
		}
		return buttons;
	},
	
	_getButton: function(button){
		var btn;
		var me = this;
		if(Ext.isString(button)){
			switch(button){
				case 'submit': 
					btn = {
						text : "提交",
						iconCls : 'fa fa-check fa-lg',
						name : "submit",
						nowStatus : "20",//提交状态
						handler : this._onSubmit
					};
					break;
				case 'close': 
					btn = {
						text : "关闭",
						iconCls : 'fa fa-times fa-1x',
						name: 'close',
						nowStatus : "10",//提交状态
						handler : function(){
							me.close();
						}
					};
					break;
				case 'tempSave': 
					btn = {
						text : "暂存",
						iconCls : 'fa fa-save fa-lg',
						name : "tempSave",
						nowStatus : "20",//提交状态
						handler : this._onTempSave
					};
					break;
			}
		}
		return btn;
	},
	
	_setConfs: function(){
		if(this._confsOveride){
			if(this._confs){
				this._confs = Ext.applyIf(this._confs, this._confsOveride );
			}else{
				this._confs = this._confsOveride;
			}
			
		}
		
	},
	_getFieldSet: function(title){
		var fs = Ext.create({
			xtype: 'fieldset',
			title: title,
			layout: 'fit'
		});
		return fs;
	},
	
	_onSubmit: function(btn){
        var me = btn.up('commonwindow'), form, filefield;
        if('submit' == btn.name && !me.openValidation){
            me.openValidation = true;
        }
        form = me.down('form');
        if(form){//判断是否采用表单提交
            filefield = form.down('filefield');
            if(filefield){
                me._submit(btn,form);
                return;
            }
        }
        //采用ajax提交
        me._submit(btn);
	},
	
	_remoteValid: function(){
		return true;
	},
	
	_submit: function(btn,form){
		var params = this.getParam(),
			me = this,
			valid = me.isValid(),
			url;
		if(this._confs){
            url = this._confs.url;
		}
		if(!valid.valid){
			App.ux.Toast.show('提示',valid.message,'ext');
			return;
		}
		
		if(!params){
			App.ux.Toast.show('提示','请修改数据后在点击提交！','i');
			return;
		}
		
		if(btn){
			if(btn.actionUrl){
				url = btn.actionUrl;				
			}
			btn.disable();
		}else{
			return;
		}
		
		if(form){
			me._formSubmit(form,btn,url,params);
		}else{
			me._ajaxSubmit(btn,url,params);
		}
		
	},
	
	_ajaxSubmit: function(btn,url,params){
		var me = this;
        var wait = Ext.Msg.show({
            width:300,
            msg: '数据提交中...',
            wait: {
                interval: 500
            }
        });
		App.ux.Ajax.request({
			url: url,
			params: params,

			success: function(response) {
                wait.hide();
                if(btn){
                    btn.enable();
                }
				me._submitSuccess(btn,response);
			},
			failure: function(response){
                wait.hide();
                if(btn){
                    btn.enable();
                }
				me._submitFailure(btn,response);
			}
		});
	},
	
	_formSubmit: function(form, btn,url,params){
		var me = this;
		if(!form){
			console.log('错误：使用form提交时，缺少Form对象。_submit(btn,form)需要传入btn和form参数');
			return;
		}
		
		form.submit({
			url:url,
            clientValidation: false,
			method: 'POST',
			waitMsg:"数据提交中...",
			params:params,
			success: function(form, action) {
                if(!action.response){
                    return;
                }
				var response = Ext.decode(action.response.responseText);
                if(btn){
                    btn.enable();
                }
				if(response.success){
					me._submitSuccess(btn,response,action);
				}else{
					if(obj.errorMessage) {
						App.ux.Toast.show('提示',response.errorMessage,'e');
					}
					me._submitFailure(btn,response,action);
				}
				
			},
			failure: function(form, action) {
				if(!action.response){
					return;
				}
				var response = Ext.decode(action.response.responseText);
				if(response.errorMessage) {
					App.ux.Toast.show('提示',response.errorMessage,'e');
				}
                if(btn){
                    btn.enable();
                }
				me._submitFailure(btn,response);
				
			}
		});
	},
	
	_submitSuccess: function(btn,response,options){
		if(btn){
            if(this.autoPrompt){
                App.ux.Toast.show('提示',btn.text + '成功！','s');
            }
		}
		if(this._targetObject){
			this._targetObject._search();
		}

		this.close();
	},
	
	_submitFailure: function(btn,response,options){
		var fileFileds = this.query('commonFileFieldExp');
        if(fileFileds && fileFileds.length > 0){
			var temp;
			for(var i=0; i<fileFileds.length; i++){
				temp = fileFileds[i].down("container[name=attName]");
				if(!temp.readOnly){
					temp.removeAll();
				}
			}
		}
	},
	
	_onTempSave: function(btn){
		var me = btn.up('commonwindow');
		me._onSubmit(btn);
	},
	
	getParam: function(){
		return this.getEncodeParams();
	},
	
	getValues: function(){
		var value = {}, i, temp,
			items = this.query('component[isParam=true]');
		for(i=0; i<items.length; i++){
			temp = items[i];
			if(temp.name && !value.hasOwnProperty(temp.name)){
				value[temp.name] = temp.getValues();
			}else if(!value.hasOwnProperty(i)){
				value[i] = temp.getValues();
			}else{
				value[temp.getId()] = temp.getValues();
			}
		}
		return value;
	},
	
	isValid: function(){
		if(!this.openValidation){
			return {
				valid: true,
				message: '跳过验证</br>'
			};
		}
		
		var i, temp,valid,
			items = this.query('component[isParam=true]');
		for(i=0; i<items.length; i++){
			temp = items[i];
			if(temp.is('form')){
                valid = temp.isNewValid();
			}else{
                valid = temp.isValid();
			}

			if(Ext.isObject(valid)){
				if(!valid.valid){
					return {
						valid: false,
						message: valid.message
					};
					break;
				}
			}else if(!valid){
				return {
					valid: false,
					message: '当前页面存在不合乎内容，请仔细检查！'
				};
				break;
			}
		}
		return {
			valid: true,
			message: '验证通过'
		};
	},
	
	getParams: function(isEncode, exclude){
		var params = {} ,i, temp, val, nullFlag = true,
			items = this.query('component[isParam=true]')
			;
			
		for(i=0; i<items.length; i++){
			temp = items[i];
			if(exclude && temp.is(exclude)){
				continue;
			}
			if(temp.is('form')){
				val = temp.getValues();
				if(val.id){//首先判断有id的form，并将id指定给params参数，保证id一定存在
					params.id = val.id;
				}
			}
			
			if(this.isGetChangeValue/* this._trigger && this._trigger.name == 'u' ||  */){//编辑动作值获取改变的值
				if(isEncode && temp.is('grid')){
					val = temp.getEncodeChangeValues();
				}else{
					val = temp.getChangeValues();
				}
			}else{//其他动作获取全部数据
				if(isEncode && temp.is('grid')){
					val = temp.getEncodeValues();
				}else if(!temp.is('form')){
					val = temp.getValues();
				}
			}
			if(Ext.isEmpty(val) || Ext.Object.isEmpty(val)){
				continue;
			}
			nullFlag = false;//如果发现获取到参数val，将nullFlag标记为false
			params = Ext.applyIf(params, val);
		}
		
		return params;
	},
	getEncodeParams: function(){
		return this.getParams(true);
	},
    clearInvalid:function () {
        Ext.suspendLayouts();
        var fields = this.query('field'),i;
        for(i=0 ;i < fields.length; i++){
        	if(!fields[i].validation){
                fields[i].clearInvalid();
			}
		}
        var files = this.query('commonFileFieldExp');
        for(i=0 ;i < files.length; i++){
            files[i].clearInvalid();
        }
        Ext.resumeLayouts(true);
    },
    hideAll:function () {
        for(var i=0; i<this.items.items.length; i++){
            this.items.items[i].hide();
            this.items.items[i].disable();
        }
    },
    /**
	 * 清空name为id的textfield的值，复制新建功能会调用该方法。
     */
	clearIdField:function () {
		var idField = this.down('textfield[name=id]');
		if(idField){
            idField.setValue('');
		}
    }
});